package org.mcjug.locationmailer.activity;

import oauth.signpost.OAuth;

import org.mcjug.locationmailer.R;
import org.mcjug.locationmailer.db.StatusMessageDatabaseHelper;
import org.mcjug.locationmailer.oauth.tokens.OauthActivity;
import org.mcjug.locationmailer.service.LocationService;
import org.mcjug.locationmailer.util.AlarmManagerUtil;
import org.mcjug.locationmailer.util.Constants;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class LocationMailerActivity extends Activity {
	private static final String TAG = LocationMailerActivity.class.getSimpleName();

	private ListView locationListView;
	private SharedPreferences prefs;

	private StatusMessageDatabaseHelper statusMessageHelper;
	private Cursor cursor;
	private SimpleCursorAdapter cursorAdapter;
	
	private int locationListDisplaySize;	
	private LocationUpdateReceiver locationUpdateReceiver;
	private LocationListViewBinder locationListViewBinder;
	
	// Database columns for location list
	private static final String[] FROM = { 
		StatusMessageDatabaseHelper.C_CREATED_DATE,
		StatusMessageDatabaseHelper.C_ADDRESS,
		StatusMessageDatabaseHelper.C_LATITUDE,
		StatusMessageDatabaseHelper.C_LONGITUDE,
	};
	
	// UI fields for location list
	private static final int[] TO = {
		R.id.textCreatedDate,
		R.id.textAddress,
		R.id.textLatitude,
		R.id.textLongitude
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.locationmailer);
		
		// Register for preferences updates
 	    setupPrefs();
	    
	    // Status Message database helper
	    statusMessageHelper = new StatusMessageDatabaseHelper(getApplicationContext());
    
		// Check Gmail Authorization
		checkOAuth(prefs);
	     
		// Populate location list
	    setupLocationList();
	    
	    // Allow user to start/stop email sending
	    setupEmailSending();	    
		
	    // Display update interval
	    setUpdateIntervalText();
	}

	private void setupPrefs() {
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
			public synchronized void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
				// Location update interval changed
				if (key.equals(Constants.PREFS_LOCATION_UPDATE_INTERVAL_KEY)) {
					AlarmManagerUtil.resetAlarm(getApplicationContext());
					setUpdateIntervalText();
					
			    // Location list display size changed
				} else if (key.equals(Constants.PREFS_LOCATION_LIST_DISPLAY_SIZE_KEY)) {
		        	updateLocationList();
		        }
			}    
		});
	}
	
	private void setUpdateIntervalText() {
		TextView intervalTextView = (TextView) findViewById(R.id.textInterval);
		long interval = AlarmManagerUtil.getInterval(getApplicationContext());
		if (interval == Constants.LOCATION_UPDATE_INTERVAL_NONE) {
			intervalTextView.setText(getString(R.string.noInterval));
		} else {
			long mins = interval / (1000 * 60);
			intervalTextView.setText(String.format(getString(R.string.interval), mins));
		}
	}
	
	private void setupEmailSending() {
		CheckBox startSendEmailCheckbox = (CheckBox) findViewById(R.id.startSendEmailCheckbox);
		startSendEmailCheckbox.setChecked(isStartSendEmailEnabled());
		startSendEmailCheckbox.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				CheckBox checkBox = (CheckBox)view;
				if (checkBox.isChecked()) {
					AlarmManagerUtil.updateAlarm(getApplicationContext());
				} else {
					AlarmManagerUtil.cancelAlarm(getApplicationContext());
				}
				Editor editor = prefs.edit();
				editor.putBoolean(Constants.PREFS_START_SENDING_EMAIL_KEY, checkBox.isChecked());
	            editor.commit();
			}
		});	
	}
	
	private void setupLocationList() {
		locationListView = (ListView) findViewById(R.id.listLocations);
		
		// Max entries to display in location list
		locationListDisplaySize = getLocationListDisplaySize();
		
		// Location list update receiver
		locationUpdateReceiver = new LocationUpdateReceiver();
		
		locationListViewBinder = new LocationListViewBinder();
		
		// Populate the location list
	    updateLocationList();
	}
	
	private int getLocationListDisplaySize() {
		int displaySize = Constants.LOCATION_LIST_DISPLAY_SIZE_DEFAULT;
		String locationSizeStr = prefs.getString(
				Constants.PREFS_LOCATION_LIST_DISPLAY_SIZE_KEY,
				String.valueOf(displaySize));
		try {
			displaySize = Integer.parseInt(locationSizeStr);
		} catch (NumberFormatException e) {
		}
		return displaySize;
	}
	
	public boolean isStartSendEmailEnabled() {	
		return prefs.getBoolean(Constants.PREFS_START_SENDING_EMAIL_KEY, false);
	}

 	private void checkOAuth (SharedPreferences prefs) {
 	    String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
		String tokenSecret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
		if (TextUtils.isEmpty(token) || TextUtils.isEmpty(tokenSecret)) {
			startOAuth();
		}
	}

  	private void startOAuth() {
	    startActivity(new Intent().setClass(
		    	getApplicationContext(), OauthActivity.class)
		    		.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
  	}
  	
	
	public void onResume() {
		super.onResume();
		
		// Register for location updates
		IntentFilter filter = new IntentFilter(LocationService.NEW_LOCATION_INTENT_ACTION);
		registerReceiver(locationUpdateReceiver, filter, LocationService.SEND_LOCATION_NOTIFICATIONS, null);
	}

	protected void onPause() {
		super.onPause();
		
		// Unregister the location update receiver
		unregisterReceiver(locationUpdateReceiver);
	}

	protected void onDestroy() {
		super.onDestroy();
		statusMessageHelper.close();
	}
	
	// Called first time user clicks on the menu button
	public boolean onCreateOptionsMenu(Menu menu) {
		// Create items from locationmailermenu.xml
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.locationmailermenu, menu);
		return true;
	}

	// Called when an options item is clicked
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		// Show Location Preferences screen
		case R.id.locationPrefs:
			startActivity(new Intent(getApplicationContext(), PrefActivity.class)
					.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
			break;
			
		// Clear Location List
		case R.id.clearLocationList:
			statusMessageHelper.delete();
		    updateLocationList();
			break;

		// Email Addresses
		case R.id.emailAddresses:
			startActivity(new Intent(getApplicationContext(), EmailActivity.class)
					.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
			break;
		
		// Gmail OAuth
		case R.id.gmailOAuth:
			startOAuth();
		    break;
		}
		
		return true;
	}		
	
	// Listens for location updates
	private class LocationUpdateReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			updateLocationList();
		}
	}

	private void updateLocationList() {
		if (cursor != null) {
			stopManagingCursor(cursor);
			cursor.close();
		}
		
		// Get the Top N location list entries
		cursor = statusMessageHelper.getStatusMessages(locationListDisplaySize);
		startManagingCursor(cursor);

		// Setup the adapter
		cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.locationrow, cursor, FROM, TO);
		cursorAdapter.setViewBinder(locationListViewBinder);
		locationListView.setAdapter(cursorAdapter);		
	}
}